<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenForm, useVbenModal } from '@vben/common-ui';
import { useAccessStore } from '@vben/stores';
import { getCheckCode } from '#/api/survey/manage';
import { Modal } from 'ant-design-vue';
import { createSurveyByTemplate } from '#/api/survey/template';
import { modalSchema } from './data';
import { addFullName, cloneDeep, getPopupContainer } from '@vben/utils';
import { getDeptTree } from '#/api/system/user';
const emit = defineEmits<{ reload: [] }>();
const title = computed(() => {
  return '模板预览';
});
const templatePreviewUrl = ref<string>('');
const accessStore = useAccessStore();
const token = accessStore.accessToken;
const origin = location.origin;
const templateKey = ref<string>('');
const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 90,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});
const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[1000px]',
  // 点击遮罩是否关闭
  closeOnClickModal: false,
  confirmText: '使用该模板',
  onCancel: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    templatePreviewUrl.value  = '';
    modalApi.modalLoading(true);
    const { key } = modalApi.getData();
    templateKey.value = key;
    const baseUrl =
      import.meta.env.MODE === 'development'
        ? `http://${location.hostname}:55554/#/`
        : `${origin}${import.meta.env.VITE_BASE_PREFIX}/cls-questionNair/#/`;
    // const checkCode = await getCheckCode();
    templatePreviewUrl.value = `${baseUrl}template/preview?key=${key}&token=${token}&checkCode=${123}&operateType=5&clientid=${import.meta.env.VITE_GLOB_APP_CLIENT_ID}`;
    modalApi.modalLoading(false);
  },
});
async function handleConfirm() {
  open.value = true;
}
async function handleCancel() {
  modalApi.close();
}
const open = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
async function useTemplate() {
  try {
    confirmLoading.value = true;
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = {
      ...cloneDeep(await formApi.getValues()),
      key: templateKey.value,
    };
    const newSurvey = await createSurveyByTemplate(data);
    emit('reload');
    confirmLoading.value = false;
    open.value = false;
    await handleCancel();
    const baseUrl =
      import.meta.env.MODE === 'development'
        ? `http://${location.hostname}:55554/#/`
        : `${origin}${import.meta.env.VITE_BASE_PREFIX}/cls-questionNair/#/`;
    location.href = `${baseUrl}project/form?key=${newSurvey}&token=${token}&clientid=${import.meta.env.VITE_GLOB_APP_CLIENT_ID}`;
  } catch (error) {
    console.error(error);
  } finally {
    confirmLoading.value = false;
  }
}
</script>

<template>
  <BasicModal :title="title">
    <Modal
      v-model:open="open"
      title="设置问卷信息"
      @ok="useTemplate"
      :confirmLoading="confirmLoading"
    >
      <BasicForm />
    </Modal>
    <iframe
      :src="templatePreviewUrl"
      width="100%"
      height="600px"
      frameborder="0"
    ></iframe>
  </BasicModal>
</template>
<style lang="less" scoped>
.tips {
  width: 100%;
  display: block;
  color: red;
  font-size: 12px;
  margin-top: 5px;
}
</style>
